package com.ntschy.framework.service;

import com.ntschy.common.constant.Constants;
import com.ntschy.common.core.model.LoginUser;
import com.ntschy.common.exception.CustomException;
import com.ntschy.common.exception.UserPasswordNotMatchException;
import com.ntschy.framework.manager.AsyncManager;
import com.ntschy.framework.manager.factory.AsyncFactory;
import com.ntschy.sys.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 *
 * @author ezreal_geng
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private SysUserMapper userMapper;



    /**
     * 登录验证
     *
     * @param username             用户名
     * @param password             密码
     * @param deviceIdentification 设被标示
     * @return 结果
     */
    public String login(String username, String password) {
        // 用户验证
        Authentication authentication = null;

        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名密码不匹配"));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登陆成功"));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return tokenService.createToken(loginUser);

    }

}
